'use strict';

const Service = require('egg').Service;

class IdleCategoryService extends Service {
  async create(data) {
    const { ctx } = this;
    return await ctx.model.IdleCategory.create(data);
  }

  async update(id, data) {
    const { ctx } = this;
    const category = await ctx.model.IdleCategory.findByPk(id);
    if (!category) {
      ctx.throw(404, '分类不存在');
    }
    return await category.update(data);
  }

  async deleteById(id) {
    const { ctx } = this;
    const category = await ctx.model.IdleCategory.findByPk(id);
    if (!category) {
      ctx.throw(404, '分类不存在');
    }
    
    // 检查是否有子分类
    const childCount = await ctx.model.IdleCategory.count({
      where: { parent_id: id }
    });
    if (childCount > 0) {
      ctx.throw(400, '该分类下有子分类，不能删除');
    }
    
    // 检查是否有关联的物资/设备
    const itemCount = await ctx.model.IdleItem.count({
      where: { category_id: id }
    });
    if (itemCount > 0) {
      ctx.throw(400, '该分类下有物资/设备，不能删除');
    }
    
    return await category.destroy();
  }

  async findOne(id) {
    const { ctx } = this;
    return await ctx.model.IdleCategory.findByPk(id);
  }

  async getPage(where, page, size) {
    const { ctx } = this;
    const { count, rows } = await ctx.model.IdleCategory.findAndCountAll({
      where,
      offset: (page - 1) * size,
      limit: size,
      order: [['sort', 'ASC'], ['id', 'DESC']]
    });
    return { count, rows };
  }

  async allList(where) {
    const { ctx } = this;
    return await ctx.model.IdleCategory.findAll({
      where,
      order: [['sort', 'ASC'], ['id', 'DESC']]
    });
  }

  async simpleList(where) {
    const { ctx } = this;
    return await ctx.model.IdleCategory.findAll({
      where,
      attributes: ['id', 'name', 'parent_id', 'type', 'sub_type'],
      order: [['sort', 'ASC'], ['id', 'DESC']]
    });
  }

  async getTree(query = {}) {
    const { ctx } = this;
    const { type } = query;
    const where = {};
    if (type) {
      where.type = type;
    }
    
    // 获取所有分类
    const categories = await ctx.model.IdleCategory.findAll({
      where,
      order: [['sort', 'ASC'], ['id', 'DESC']]
    });
    
    // 构建树形结构
    const categoryMap = {};
    const result = [];
    
    categories.forEach(category => {
      categoryMap[category.id] = {
        id: category.id,
        name: category.name,
        parent_id: category.parent_id,
        type: category.type,
        sub_type: category.sub_type,
        sort: category.sort,
        children: []
      };
    });
    
    categories.forEach(category => {
      if (category.parent_id === 0) {
        result.push(categoryMap[category.id]);
      } else {
        if (categoryMap[category.parent_id]) {
          categoryMap[category.parent_id].children.push(categoryMap[category.id]);
        }
      }
    });
    
    return result;
  }

  async getByType(type) {
    const { ctx } = this;
    return await ctx.model.IdleCategory.findAll({
      where: { type },
      order: [['sort', 'ASC'], ['id', 'DESC']]
    });
  }

  async getSubTypes(type) {
    const { ctx } = this;
    const categories = await ctx.model.IdleCategory.findAll({
      where: { type },
      attributes: ['sub_type'],
      group: ['sub_type'],
      order: [['sort', 'ASC']]
    });
    
    return categories.map(item => item.sub_type).filter(item => item);
  }
}

module.exports = IdleCategoryService;
